import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.io.*;
import java.security.NoSuchAlgorithmException;

public class shiyan1_7 {
    public static void main(String[] args){
        SecretKey key = funcGetKey();
        funcWriteToFile(key,"./key");
        SecretKey fileKey = funcReadFromFile("./key");
        System.out.println(fileKey.getEncoded());
    }

    public static SecretKey funcGetKey(){
        try{
            KeyGenerator AESKeyGen = KeyGenerator.getInstance("AES");
            AESKeyGen.init(256);
            return AESKeyGen.generateKey();
        }catch (NoSuchAlgorithmException e){
            e.printStackTrace();
            System.out.println("没有这个加密算法");
        }
        return null;
    }

    public static void funcWriteToFile(SecretKey key,String filename){
        try{
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename));
            oos.writeObject(key);
            oos.close();
        } catch (IOException e){
            e.printStackTrace();
        }
    }

    public static SecretKey funcReadFromFile(String filename){
        try {
            ObjectInputStream ois=new ObjectInputStream(new FileInputStream(filename));

            return (SecretKey) ois.readObject();                                       //返回对象
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
